<script setup>
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {debounce, throttle} from "lodash";
import { format } from 'timeago.js'
import {useRoute, useRouter} from 'vue-router'
import {getDraftsByPostId, saveTheDraft} from '@/api/post/post.js' // Assume this API call is defined
import { ElMessageBox } from 'element-plus'

import {ElMessage} from "element-plus";
import {getPostTopics} from "@/api/post/post.js";
import postPost from "@/views/post/PostPost.vue";


const route = useRoute()
const router = useRouter()

const topics = ref([{
  title: 'Option1',
  id: 'Option1',
},
  {
    title: 'Option2',
    id: 'Option2',
  }
])



// 应该设置一个草稿id （用于覆盖，不用覆盖，设计草稿时间线设计，可以恢复到任一历史时期）
const data = ref({
  content: '',
  contentText: '',
  picList: [],
  topicId: '',
  remark: '',
  wordNum: 0,
  isNameless: null,
  account: localStorage.getItem('account'),
  id: null
})

// 当喂true的时候就是在底部显示回到顶部，反之则反
const isUpOrNotDown = ref(false)
const scrollContainer = ref(null)

// 草稿保存时间
const draftUpdateTime = ref(new Date('2024-11-27T14:00:00'))

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()



const countWords = () => {
  data.value.wordNum = editorRef.value.getText().trim().length
}
let wordCountInterval = null


const scrollToTop = () => {
  if (scrollContainer.value) {
    scrollContainer.value.wrapRef.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
  }
}

const scrollToBottom = () => {
  if (scrollContainer.value) {
    scrollContainer.value.wrapRef.scrollTo({
      top: scrollContainer.value.wrapRef.scrollHeight,
      behavior: 'smooth'
    })
  }
}

const handleScroll = () => {
  const container = scrollContainer.value.wrapRef
  const distanceToBottom = container.scrollHeight - container.scrollTop - container.clientHeight
  isUpOrNotDown.value = distanceToBottom <= 10
}

onMounted(() => {
  // setTimeout(() => {
  //
  //   valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
  //
  // }, 1500)
  getPostTopics().then((res) => {
    console.log(res)
    topics.value = res.data
  })

  wordCountInterval = setInterval(countWords, 1000)


})
onBeforeUnmount(() => {
  // 清除定时器
  if (wordCountInterval) clearInterval(wordCountInterval)

})

// 工具栏配置
const toolbarConfig = {
  toolbarKeys: ['bold', 'underline', 'italic', 'through', 'clearStyle', 'color',
    'fontFamily', 'justifyLeft', 'justifyRight', 'justifyCenter', 'justifyJustify', 'divider', 'emotion', 'blockquote', 'headerSelect', 'redo', 'undo', 'fullScreen', 'bulletedList', 'numberedList']
}
const editorConfig = { placeholder: '请输入内容，不超过1w字...', autoFocus: true, maxlength: 10000  }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}




const handleChange = (file, picList) => {

}
const handleExceed = (files, fileList) => {
  ElMessage.error("上传文件已达上限，最多只能选择9个图片")
}

const saveDraft = throttle ( () => {
  // 发一个请求，保存一下草稿
  // 逻辑是把route里的draftId传给后端，如果是null，就生成用uuid生成一个draftId，这个draftId不是唯一的，是总时间线的一个draft

  const jsonData = {
    postId: route.params.postId,
    content: data.value.content,
    account: localStorage.getItem('account')
  }
  saveTheDraft(jsonData).then((res) => {
    router.push({ name: 'postPost', params: { postId: res.data }})
    ElMessage.success('保存成功')
  })

} ,500)

const postThePost = throttle ( () => {
  // 发一个请求，直接将该贴子发布
  data.value.id = route.params.postId
  if (data.value.contentText.toString().trim() === "") {
    data.value.contentText = editorRef.value.getText().substring(0, 250)
  }
  postPost(data.value).then((res) => {
    ElMessage.success('发布成功！')
  })
} ,500)
const drafts = ref([])

// 在 script setup 中添加
const dialogVisible = ref(false)

const showDraftsByTimes = async () => {
  const postId = route.params.postId
  if (!postId) return

  try {
    const response = await getDraftsByPostId(postId)
    drafts.value = response.data
    dialogVisible.value = true
  } catch (error) {
    console.error(error)
  }
}

const selectedDraft = ref()

const selectDraft = (draft) => {
  selectedDraft.value = draft
}

const restoreDraft = () => {

  const draft = drafts.value.find(d => d.id === selectedDraft.value.id)

  if (draft) {
    data.value.content = draft.content
    dialogVisible.value = false

  }

}

onMounted(() => {
  
})
</script>



<template>
  <el-scrollbar ref="scrollContainer" @scroll="handleScroll" style="background: #f9f9f9;" height="100vh">
    <div id="container" class="container">
      <div style="position: sticky;z-index: 10;top: 0;scale: 1.2;background: white;display: flex;flex-direction: column;align-items: center;width: 83.33vw;box-sizing: border-box">
        <Toolbar
            style="margin: 0 auto"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
        />
      </div>
      <div style="padding: 0 20px 15px;background: #ffffff;margin: 30px 0;">
        <Editor
            style="box-sizing: border-box;min-height: 650px;width: 800px;
          border-bottom: 1px solid #dedede;"
            v-model="data.content"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleCreated"
        />
        <div class="config-container">
          <p style="line-height: 61px;font-size: 17px;">发布设置</p>
          <div style="display: flex;flex-direction: column;gap: 10px">
            <div class="config-item">
              <div style="padding-top: 8px">添加图片</div>
              <div style="flex: 1">
                <el-upload
                    action="#" list-type="picture-card" :auto-upload="false"
                    :limit="9"
                    :on-change="handleChange"
                    :file-list="data.picList"
                    :on-exceed="handleExceed"
                >
                  <el-icon><Plus /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">
                      只能选择图片文件
                    </div>
                  </template>
                </el-upload>
              </div>
            </div>

            <div style="align-items: center" class="config-item">
              <div>帖子摘要</div>
              <div style="flex: 1">
                <textarea v-model="data.contentText" maxlength="250" placeholder="摘要：会在推荐、列表等场景外露，帮助读者快速了解内容，默认添加正文前250字"></textarea>
              </div>
            </div>

            <div style="align-items: center" class="config-item">
              <div>热点话题</div>
              <div style="flex: 1">
                <el-select
                    v-model="data.topicId"
                    filterable
                    placeholder="请选择"
                    style="width: 240px"
                >
                  <el-option
                      v-for="(item, index) in topics" :key="index"
                      :label="item.title" :value="item.id"
                  />
                </el-select>
              </div>
            </div>

            <div style="align-items: center" class="config-item">
              <div>备注</div>
              <el-input v-model="data.remark" size="large" style="font-size: 14px;width: 400px" maxlength="30" placeholder="可输入不超过30字的备注，备注只有你自己可见" />
            </div>

            <div style="" class="config-item">
              <div>身份选择</div>
              <div style="flex: 1">
                <el-select
                    v-model="data.isNameless" placeholder="请选择" style="width: 240px">
                  <el-option value="实名"/>
                  <el-option value="匿名"/>
                </el-select>
              </div>
            </div>

          </div>
        </div>

      </div>

      <footer>

        <div @click="scrollToTop" style="cursor:pointer;display: flex;align-items: center;gap: 3px" v-if="isUpOrNotDown"><span>回到顶部</span><el-icon><ArrowUp /></el-icon></div>
        <div @click="scrollToBottom" style="cursor:pointer;display: flex;align-items: center;gap: 3px" v-else><span>发布设置</span><el-icon><ArrowDown /></el-icon></div>
        <span style="margin: 0 30px">字数：{{ data.wordNum }}</span>

        <div @click="showDraftsByTimes" style="cursor: pointer;display: flex;align-items: center;margin-left: auto">
          {{ format(draftUpdateTime, 'zh_CN') }} · 草稿已保存
          <svg width="16px" height="16px" viewBox="0 0 24 24" style="margin-left: 3px;margin-right: 20px" fill="#67C23A"><path d="M10.5 4.375c-1.845 0-3.578 1.129-4.631 2.498-.778 1.01-1.323 2.357-1.092 3.638a4.35 4.35 0 0 0-2.114 1.152c-.843.842-1.288 2.013-1.288 3.337 0 2.8 2.41 4.625 4.625 4.625h3a.875.875 0 0 0 0-1.75H6c-1.386 0-2.875-1.175-2.875-2.875 0-.926.305-1.63.775-2.1.47-.47 1.174-.775 2.1-.775a.875.875 0 0 0 .728-1.36c-.442-.663-.315-1.73.528-2.825.822-1.069 2.089-1.815 3.244-1.815 1.338 0 2.178.344 2.717.712.546.375.845.816 1.043 1.13a.875.875 0 0 0 1.48-.934c-.24-.378-.691-1.062-1.535-1.64-.852-.583-2.043-1.018-3.705-1.018Z"></path><path d="M22.427 11.804a.875.875 0 0 0-1.354-1.108l-6.138 7.502-3.066-3.067a.875.875 0 1 0-1.238 1.238l3.75 3.75a.875.875 0 0 0 1.296-.065l6.75-8.25Z"></path></svg>
        </div>
        <button @click="saveDraft" style="background: white;color: rgba(30,30,33);border: 1px solid rgba(30,30,33);opacity: 0.6;box-sizing: border-box">保存草稿</button>
        <button @click="postThePost" style="background: #e96161;color: white;margin-left: 15px">发布帖子</button>

      </footer>

    </div>
  </el-scrollbar>

  <el-dialog
      v-model="dialogVisible"
      width="800px"
      :show-close="true"
      :close-on-click-modal="false"
      class="draft-dialog"
  >
    <template #header>
      <div style="
    font-size: 17px;
    font-weight: 600;
    line-height: 24px;
    padding: 10px 0;">草稿备份</div>
    </template>
    <div class="draft-container">
      <!-- 左侧时间列表 -->
      <div class="time-list">
        <div
            v-for="draft in drafts"
            :key="draft.id"
            class="time-item"
            :class="{ active: selectedDraft?.id === draft.id }"
            @click="selectDraft(draft)"
        >
          <div class="time-dot">•</div>
          <div class="time-info">
            {{ new Date(draft.updateTime).toLocaleString() }}
          </div>
        </div>
      </div>

      <!-- 右侧预览区域 -->
      <div class="preview-area">
        <div class="preview-content" v-html="selectedDraft?.content || '请选择要预览的草稿'"></div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="restoreDraft"
            :disabled="!selectedDraft"
        >
          恢复此版本
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.container {
  background: #f2f2f2;
  display: flex;
  flex-direction: column;
  align-items: center;
}
button {
  height: 40px;
  padding: 8px 16px;
  line-height: 22px;
  border-radius: 20px;
  font-size: 16px;
  outline: none;
  cursor: pointer;
  border: 0;
  opacity: 0.8;
}
button:hover {
  opacity: 1!important;
}
footer {
  width: 760px;
  padding: 0 calc(50vw - 380px);
  height: 60px;
  line-height: 60px;
  background: white;
  border-top: 1px solid #e4e4e4;
  position: sticky;
  bottom: 0;
  font-size: 14px;
  color: #8d8d8d;
  display: flex;
  align-items: center;
}
.config-container {
  color: #373a40;
}
.config-item {
  display: flex;
  gap: 5px;
  margin-top: 10px;
  width: 800px;
}
.config-item>:first-child {
  font-size: 15px;
  padding-left: 10px;
  width: 110px;
  text-align: left;
}

.draft-dialog :deep(.el-dialog__body) {
  padding: 0;
}
.draft-container {

}
.draft-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.draft-dialog :deep(.el-dialog__header) {
  margin: 0;
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.draft-dialog :deep(.el-dialog__footer) {
  padding: 10px 20px;
  border-top: 1px solid #e4e7ed;
}

.draft-container {
  display: flex;
  height: 500px;
}

/* 左侧时间列表样式 */
.time-list {
  width: 240px;
  border-right: 1px solid #e4e7ed;
  overflow-y: auto;
  background: #f5f7fa;
}

.time-item {
  padding: 15px 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
  position: relative;
}

.time-item:hover {
  background-color: #ffffff;
}

.time-item.active {
  background-color: #ffffff;
  color: #409eff;
}

.time-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 2px;
  background-color: #409eff;
}

.time-dot {
  margin-right: 8px;
  color: #409eff;
  font-weight: bold;
}

.time-info {
  font-size: 14px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

/* 右侧预览区域样式 */
.preview-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #ffffff;
}

.preview-content {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
}

.preview-content :deep(p) {
  margin: 0;
  padding: 5px 0;
}

.preview-content :deep(img) {
  max-width: 100%;
  height: auto;
}

/* 空状态提示 */
.empty-preview {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
}

/* 底部按钮样式 */
.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.time-list::-webkit-scrollbar,
.preview-area::-webkit-scrollbar {
  width: 6px;
}

.time-list::-webkit-scrollbar-thumb,
.preview-area::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.time-list::-webkit-scrollbar-track,
.preview-area::-webkit-scrollbar-track {
  background: transparent;
}
textarea {
  resize: none;
  outline: none;
  box-sizing: border-box;
  min-height: 66px;
  width: 100%;
  display: block;
  padding: 7px;
  color: #333;
  font-size: 14px;
  font-family: poppin, Tahoma, Arial, 微软雅黑, sans-serif;
  white-space: pre-wrap;
  border: 1px solid #ececec;
  background-color: #f5f5f5;
}
</style>
